﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using SportsStore.Domain.Abstract;
using SportsStore.Domain.Entities;
using SportsStore.WebUI.Models;

namespace SportsStore.WebUI.Controllers
{
    public class ProductController : Controller
    {
        private IProductRepository repository;

        public int PageSize = 4;

        public ProductController(IProductRepository productRepository)
        {
            this.repository = productRepository;
        }

        public ViewResult List(string category, int page = 1)
        {
            ProductListViewModel model = new ProductListViewModel()
                                         {
                                             Products =
                                                 repository.Products
                                                 .Where(p => category == null || p.Category == category)
                                                 .OrderBy(p => p.ProductId)
                                                 .Skip((page - 1)*PageSize)
                                                 .Take(PageSize),
                                             PagingInfo = new PagingInfo
                                                          {
                                                              CurrentPage = page,
                                                              ItemPerPage = PageSize,
                                                              TotalItems = category==null ? repository.Products.Count():repository.Products.Where(x=>x.Category==category).Count()
                                                          },
                                             CurrentCategory = category
                                         };
            return View(model);
        }

        public FileContentResult GetImage(int productId)
        {
            Product prod = repository.Products.FirstOrDefault(x => x.ProductId == productId);
            if (prod != null)
            {
                return File(prod.ImageData, prod.ImageMimeType);
            }
            else
            {
                return null;
            }
        }
    }
}
